﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.ComponentModel;
using Windows.Storage;
using CC98.Security;
using CC98.Storage;

namespace CC98.Network
{
    /// <summary>
    /// Network Session
    /// NOTE:
    ///     The cookie is static at this stage
    /// </summary>
    [DataContract(Namespace = Utility.SchemaNamespace)]
    public sealed class Session : IComplexSettingEntity
    {
        internal Session(string username , CookieCollection cookies, DateTime? loginTime)
        {
            this.Username = username;
            this.Cookies = cookies;
            this.LoginTime = loginTime;
        }

        public Session(ApplicationDataContainer container)
        {
            if (container == null)
                throw new ArgumentNullException("container");
            this.Read(container);
        }

        [DataMember]
        public string Username { get; private set; }

        [DataMember]
        internal CookieCollection Cookies { get; private set; }

        [DataMember]
        internal DateTime? LoginTime { get; private set; }

        private void Read(ApplicationDataContainer container)
        {
            this.Username = (string)container.Values["username"];
            if (container.Values.ContainsKey("loginTime"))
                this.LoginTime = new DateTime((long)container.Values["loginTime"]);
            if (container.Containers.ContainsKey("cookies"))
            {
                this.Cookies = new CookieCollection();
                var cookieContainer = container.Containers["cookies"];
                foreach (var cookieValue in container.Values)
                    Cookies.Add(SettingHelper.ReadCookie((ApplicationDataCompositeValue)cookieValue.Value));
            }
        }

        public void Write(ApplicationDataContainer container)
        {
            if (container == null)
                throw new ArgumentNullException("container");

            container.Values["username"] = this.Username;
            if(this.LoginTime != null)
                container.Values["loginTime"] = this.LoginTime.Value.Ticks;

            if (this.Cookies != null)
            {
                var cookieContainer = container.CreateContainer("cookies", ApplicationDataCreateDisposition.Always);
                foreach (Cookie cookie in this.Cookies)
                {
                    cookieContainer.Values[cookie.Name] = cookie.WriteCookie();
                }
            }
        }
    }
}
